﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Collections;
using System.Threading;

namespace LambdaExtensions.WinForms
{
    public partial class BackgroundOperation : Form
    {

        protected BackgroundOperation()
        {
            InitializeComponent(); 
        }

        private void BackgroundOperation_Load(object sender, EventArgs e)
        {
            backgroundWorkerDoWork.RunWorkerAsync();
        }

        private void backgroundWorkerDoWork_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            progressBar.Value++;

        }

        private void backgroundWorkerDoWork_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            Close();
        }


        private void buttonCancel_Click(object sender, EventArgs e)
        {
            buttonCancel.Enabled = false;
            backgroundWorkerDoWork.CancelAsync();
        }

        public static void ForEach<T>(IEnumerable<T> source, Action<T> action)
        {
            var b = new BackgroundOperation();
            bool bSuccessfullRun = false;
            b.progressBar.Maximum = source.Count();

            if (b.progressBar.Maximum == 1)
                b.progressBar.Style = ProgressBarStyle.Marquee;

            b.backgroundWorkerDoWork.DoWork += (arg, eventArgs) =>
                {
                    foreach (var i in source)
                    {
                        action(i);
                        if (eventArgs.Cancel)
                            return;

                        b.backgroundWorkerDoWork.ReportProgress(1);
                    }
                    bSuccessfullRun = true;
                };

            b.ShowDialog();

            if (!bSuccessfullRun)
                throw new ThreadInterruptedException();

        }


    }
}
